/**
 * 等待唤醒机制
 * 生产者和消费者
 * 线程轮流交替执行
 */
public class WaitWakeUp {
    public static void main(String[] args) {
        Cook c = new Cook();
        Food f = new Food();
        c.setName("厨师");
        f.setName("吃货");
        c.start();
        f.start();

    }

    static class Food extends Thread{
        @Override
        public void run() {
            while(true){
                synchronized (Desk.object){
                    if (Desk.count == 0){
                        break;
                    }
                    else{
                        if (Desk.foodFlag == 0){
                            try {
                                Desk.object.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        // 食物减一
                        Desk.count --;
                        System.out.println("吃货还能吃" + Desk.count + "碗饭");
                        // 修改状态
                        Desk.foodFlag = 0;
                        // 唤醒厨师继续做
                        Desk.object.notifyAll();
                    }
                }
            }
        }
    }

    static class Cook extends Thread{
        @Override
        public void run() {
            while(true){
                synchronized (Desk.object){
                    if (Desk.count == 0){
                        break;
                    }
                    else{
                        // 判断是否有无食物
                        if (Desk.foodFlag == 1){
                            // 有食物继续等待
                            try {
                                Desk.object.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        else{
                            System.out.println("厨师做了一碗面条");
                            // 修改状态
                            Desk.foodFlag = 1;
                            // 唤醒厨师继续做
                            Desk.object.notifyAll();
                        }

                    }
                }
            }
        }
    }


    static class Desk{
        // 还能吃几碗
        private static Integer count = 10;
        // 状态；0:无食物，1:有食物
        private static Integer foodFlag = 0;
        // 锁对象
        private static Object object = new Object();
    }




}
